package player

import (
	"fmt"
	"game/game-db/mysql/dao"
	"sync"
	"tcs-server/tcs-game-server/src/foundation/starting"
	player "tcs-server/tcs-game-server/src/module/player/model"
)

var singleton *playerService = &playerService{}
var once sync.Once

func Service() *playerService {
	once.Do(func() {
		var service playerService
		service.idao = dao.NewDefaultBaseDao[*player.Player](starting.DataDB, &player.Player{})
		singleton = &service
	})
	return singleton
}

type playerService struct {
	userIdToPlayerId sync.Map //<后台用户ID_服务器ID，玩家ID>
	nickMap          sync.Map //<昵称，玩家ID>
	idao             dao.IDao[*player.Player]
}

func (s *playerService) GetEntity(playerId int64) *player.Player {
	return s.idao.GetByPrimaryKey(playerId)
}

func (s *playerService) GetIdByUserIdAndServerId(userId string, serverId int32) *player.Player {
	playerKey := fmt.Sprintf("%s_%v", userId, serverId)
	playerId, exist := s.userIdToPlayerId.Load(playerKey)
	if !exist {
		return nil
	}
	return s.GetEntity(playerId.(int64))
}

func (s *playerService) Insert(player *player.Player) {
	s.idao.Insert(player)
	playerKey := fmt.Sprintf("%s_%v", player.UserId, player.ServerId)
	s.userIdToPlayerId.Store(playerKey, player.Id)
	s.nickMap.Store(player.Nick, 1)
}
